package com.fanshuai.spring.boot.config;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.kafka.core.*;

import java.util.HashMap;
import java.util.Map;

@ConditionalOnProperty(value = "spring.kafka.enabled", matchIfMissing = false)
@Configuration
public class KafkaConfig {
    @Value("${spring.kafka.producer.bootstrap-servers}")
    private String servers;

    @Value("${spring.kafka.consumer.group-id:${spring.application.name}}")
    private String groupId;

    @Value(("${spring.kafka.consumer.enable-auto-commit}"))
    private boolean autoCommit;

    private Map<String, Object> producerProperties() {
        Map<String, Object> map = new HashMap<>();
        map.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        map.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        map.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        map.put(ProducerConfig.ACKS_CONFIG, "all");
        map.put(ProducerConfig.LINGER_MS_CONFIG, "10");
        return map;
    }

    private ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerProperties());
    }

    @Bean
    @Primary
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    private Map<String, Object> consumerMap() {
        Map<String, Object> map = new HashMap<>();
        map.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        map.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        map.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        map.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);

        map.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, autoCommit);
        return map;
    }

    @Bean
    @Primary
    public ConsumerFactory consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerMap());
    }
}
